﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Interactivity;
using System.Windows;
using System.ComponentModel.Composition;

namespace Codeplex.KinkumaFramework
{
    public class InjectToViewModelBehavior : Behavior<FrameworkElement>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.DataContextChanged += AssociatedObject_DataContextChanged;
            this.Inject();
        }

        protected override void OnDetaching()
        {
            this.AssociatedObject.DataContextChanged -= AssociatedObject_DataContextChanged;
            base.OnDetaching();
        }

        private void AssociatedObject_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            this.Inject();
        }

        private void Inject()
        {
            if (ContainerHolder.Container == null)
            {
                return;
            }

            if (this.AssociatedObject.DataContext == null)
            {
                return;
            }

            ContainerHolder.Container.SatisfyImportsOnce(this.AssociatedObject.DataContext);
        }
    }
}
